import axios, { AxiosRequestConfig } from 'axios'

import { getValueInStorage } from '../storageUtil'
import md5 from 'crypto-js/md5'
import { ContentTypeEnum } from './httpEnum'

let option: AxiosRequestConfig = {
    baseURL: `http://192.168.31.45:8105`,
    withCredentials: true,
    headers: {
        "Content-Type": ContentTypeEnum.JSON,
        "Accept": "*/*",
        "Connection": "keep-alive",
        // "Accept": "application/json, text/plain, */*",
    },
    timeout: 30000,
}

const service = axios.create(option)
type Recordable<T = any> = Record<string, T>;


// 前置拦截器（发起请求之前的拦截）
service.interceptors.request.use(

    async (request) => {
        const token = getValueInStorage<String>('token', '');

        // jwt token 
        (request as Recordable).headers.Authorization = token ? `${token}` : '';
        //接口验证
        const API_SECRET = "dibin@888";
        const timestamp: number = Date.parse(new Date().toString()) / 1000;
        (request as Recordable).headers["verify-time"] = timestamp as any;
        (request as Recordable).headers["verify-encrypt"] = md5(API_SECRET + timestamp) as any;
        return request
    },
    (error) => {
        // console.log(error, '前置拦截器（发起请求之前的拦截）')
        return Promise.reject(error)
    }
)

// 后置拦截器（获取到响应时的拦截）
service.interceptors.response.use(
    (response) => {
        /**
         * 根据你的项目实际情况来对 response 和 error 做处理
         * 这里对 response 和 error 不做任何处理，直接返回
         */
        //这里需要code review
        // if (statusCode.includes(response.status)) {
        return Promise.resolve(response.data)
        // } else {
        //     return Promise.reject(response.data)
        // }
    },
    (error) => {
        console.log(error, '后置拦截器（获取到响应时的拦截）')
        return Promise.reject(error.response.data)
    }
)

function get(url: string, params?: any): Promise<any> {
    return new Promise((resolve, reject) => {
        service.get(url, { params })
            .then((res: any) => {
                resolve(res)
            })
            .catch(err => {
                reject(err)
            })
    })
}


function post<T>(url: string, params?: any, config?: AxiosRequestConfig): Promise<any> {


    return new Promise((resolve, reject) => {
        service.post(url, params, config)
            .then((res) => {
                resolve(res)
            })
            .catch(err => {
                console.log('err', err)
                // post(API.ERRORLOG, { err: err.data.msg, url }).then((res: any) => console.log('res', res)).catch((err: any) => console.log('ERRORLOG', err))
                reject(typeof err)
            })
    })
}


/**
 * post 请求
 * @param url 
 * @param params 
 * @returns 
 */
const FetchPost = <T>(url: string, params?: any, config?: RequestInit): Promise<any> => {
    let U = `http://192.168.31.57:3000` + url
    console.log(U);

    return new Promise((resolve, reject) => {

        fetch(U, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Connection": "keep-alive",
                "Accept": "*/*"
            },
            body: params,
            ...config
        })
            .then(response => response.json())
            .then(res => resolve(res))
            .catch(err => reject(err))
    })
}



/**
 * 文件上传
 * @param url string
 * @param datas 
 * @returns 
 */
const UploadRequest = (url: string, datas: FormData) => {
    const params = {
        method: 'post',
        body: datas,
        headers: {
            'Content-Type': 'multipart/form-data',
            'childPath': `${url}`
        },
        timeout: 5000 // 5s超时
    };

    return fetch(`/store/upload`, params)
        .then(response => response.json())
        .then(data => {
            console.log(data);

            return data
        })
        .catch(error => {
            return error
        })
}

export const defHttp = {
    post,
    get,
    UploadRequest,
    FetchPost
}
